package com.example.yls.demoa;

import android.content.Context;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.graphics.Canvas;
import android.graphics.Paint;
import android.graphics.Point;
import android.os.Bundle;
import android.os.Parcelable;
import android.support.annotation.Nullable;
import android.util.AttributeSet;
import android.util.Log;
import android.view.MotionEvent;
import android.view.View;
import android.widget.Toast;

import java.util.ArrayList;
import java.util.List;

import cn.bmob.v3.BmobQuery;
import cn.bmob.v3.exception.BmobException;
import cn.bmob.v3.listener.FindListener;
import cn.bmob.v3.listener.SaveListener;
import cn.bmob.v3.listener.UpdateListener;

import static android.content.ContentValues.TAG;

/**
 * Created by yls on 2019/5/19.
 */

public class MyView extends View {
    private int mPanelWidth;
    private float mLineHeight;
    private int MAX_LINE = 10;
    private int MAX_COUNT_IN_LINE = 5;

    private Paint paint = new Paint();

    private Bitmap mWhitePiece;
    private Bitmap mBlackPiece;

    private float radioPieceOfLineHeight = 3 * 1.0f / 4;

    //白棋先手
    private boolean mIsWhite = true;
    private ArrayList<Point> mWhiteArray = new ArrayList<>();
    private ArrayList<Point> mBlackArray = new ArrayList<>();

    private boolean mIsGameOver;
    private boolean mIsWhiteWinner;
    private String matchId = "1234567";

    public MyView(Context context, @Nullable AttributeSet attrs) {
        super(context, attrs);

        //setBackgroundColor(0x44ff0000);
        init();
    }

    private void init() {
        paint.setAntiAlias(true);
        paint.setDither(true);
        paint.setStyle(Paint.Style.STROKE);
        paint.setColor(0x88000000);

        //读取图片
        mWhitePiece = BitmapFactory.decodeResource(getResources(), R.drawable.stone_w2);
        mBlackPiece = BitmapFactory.decodeResource(getResources(), R.drawable.stone_b1);
    }

    @Override
    protected void onMeasure(int widthMeasureSpec, int heightMeasureSpec) {
        super.onMeasure(widthMeasureSpec, heightMeasureSpec);

        int widthSize = MeasureSpec.getSize(widthMeasureSpec);
        int widthMode = MeasureSpec.getMode(widthMeasureSpec);

        int heightSize = MeasureSpec.getSize(heightMeasureSpec);
        int heightMode = MeasureSpec.getMode(heightMeasureSpec);

        //设置宽度最小的范围值
        int width = Math.min(widthSize, heightSize);

        //若宽度不明确
        if(widthMode == MeasureSpec.UNSPECIFIED){
            width = heightSize;
        } else if(heightMode == MeasureSpec.UNSPECIFIED){
            width = widthSize;
        }

        //正方体
        setMeasuredDimension(width, width);
    }

    @Override
    protected void onSizeChanged(int w, int h, int oldw, int oldh) {
        super.onSizeChanged(w, h, oldw, oldh);

        mPanelWidth = w;
        mLineHeight = mPanelWidth * 1.0f / MAX_LINE;

        int pieceWidth = (int) (mLineHeight * radioPieceOfLineHeight);
        Log.e(TAG, "行高：mLineHeight = " + mLineHeight +
                " 棋子的大小：pieceWidth = " + pieceWidth);

        mWhitePiece = Bitmap.createScaledBitmap(mWhitePiece, pieceWidth, pieceWidth, false);
        mBlackPiece = Bitmap.createScaledBitmap(mBlackPiece, pieceWidth, pieceWidth, false);
    }

    @Override
    public boolean onTouchEvent(MotionEvent event) {
        //若结束，停止触摸事件
        if(mIsGameOver) return false;

        if(event.getAction() == MotionEvent.ACTION_UP){
            int x = (int) event.getX();
            int y = (int) event.getY();

            Point p = getValidPoint(x, y);
            Log.e(TAG, "棋子的位置：p = " + p);

            //判断当前位置是否有棋子
            if (mWhiteArray.contains(p) || mBlackArray.contains(p)) {
                return false;
            }

            if(mIsWhite){
                mWhiteArray.add(p);
            }else {
                mBlackArray.add(p);
            }
            invalidate();
            mIsWhite = !mIsWhite;

            //将数据保存到Bmob中
            saveToBmob();
        }

        //表示触发了这一事件
        return true;
    }

    private void saveToBmob() {
        BmobQuery<WuziData> wuziDataBmobQuery = new BmobQuery<>();
        wuziDataBmobQuery.addWhereEqualTo("matchId", matchId);
        wuziDataBmobQuery.findObjects(new FindListener<WuziData>() {
            @Override
            public void done(List<WuziData> list, BmobException e) {
                if(e == null && list != null && list.size() > 0){
                    WuziData wuziData = list.get(0);
                    wuziData.setmBlackArray(mBlackArray);
                    wuziData.setmWhiteArray(mWhiteArray);
                    wuziData.setmIsGameOver(mIsGameOver);
                    wuziData.setmIsWhite(mIsWhite);
                    wuziData.setmIsWhiteWinner(mIsWhiteWinner);
                    wuziData.update(new UpdateListener() {
                        @Override
                        public void done(BmobException e) {

                        }
                    });
                }else {
                    //没有表或没有局的情况
                    WuziData wuziData = new WuziData();
                    wuziData.setMatchId(matchId);
                    wuziData.setmBlackArray(mBlackArray);
                    wuziData.setmWhiteArray(mWhiteArray);
                    wuziData.setmIsGameOver(mIsGameOver);
                    wuziData.setmIsWhite(mIsWhite);
                    wuziData.setmIsWhiteWinner(mIsWhiteWinner);
                    wuziData.save(new SaveListener<String>() {
                        @Override
                        public void done(String s, BmobException e) {
                            Log.e(TAG, "e : " + e.getMessage() );
                        }
                    });
                }
            }
        });
    }

    //一个点进行取整，确定在某个范围内点击，棋子的圆心落在交叉点上
    private Point getValidPoint(int x, int y) {
        return  new Point((int) (x/mLineHeight), (int) (y/mLineHeight));
    }

    @Override
    protected void onDraw(Canvas canvas) {
        super.onDraw(canvas);

        drawBoard(canvas);

        drawPieces(canvas);

        checkGameOver();
    }

    private void checkGameOver() {
        boolean witheWin = checkFiveInLine(mWhiteArray);
        boolean blackWin = checkFiveInLine(mBlackArray);

        if(witheWin || blackWin){
            mIsGameOver = true;
            mIsWhiteWinner = witheWin;

            String text = mIsWhiteWinner?"白棋胜利":"黑棋胜利";
            Toast.makeText(getContext(), text, Toast.LENGTH_SHORT).show();
        }

    }

    private boolean checkFiveInLine(List<Point> points) {
        for(Point p: points){
            int x = p.x;
            int y = p.y;

            boolean win = checkHorizontal(x, y, points);
            if(win) return true;

            win = checkVertical(x, y, points);
            if(win) return true;

            win = checkLeftDiagonal(x, y, points);
            if(win) return true;

            win = checkRightDiagonal(x, y, points);
            if(win) return true;
        }
        return false;
    }

    //横向判断是否连成相同的5个棋子
    private boolean checkHorizontal(int x, int y, List<Point> points) {
        int count = 1;
        //左
        for(int i = 1; i<MAX_COUNT_IN_LINE; i++){
            if(points.contains(new Point(x-i, y))){
                count++;
            }else {
                break;
            }
        }
        if(count == MAX_COUNT_IN_LINE) return true;
        //右
        for(int i = 1; i<MAX_COUNT_IN_LINE; i++){
            if(points.contains(new Point(x+i, y))){
                count++;
            }else {
                break;
            }
        }
        if(count == MAX_COUNT_IN_LINE) return true;

        return false;
    }

    private boolean checkVertical(int x, int y, List<Point> points) {
        int count = 1;
        //上
        for(int i = 1; i<MAX_COUNT_IN_LINE; i++){
            if(points.contains(new Point(x, y-i))){
                count++;
            }else {
                break;
            }
        }
        if(count == MAX_COUNT_IN_LINE) return true;
        //下
        for(int i = 1; i<MAX_COUNT_IN_LINE; i++){
            if(points.contains(new Point(x, y+i))){
                count++;
            }else {
                break;
            }
        }
        if(count == MAX_COUNT_IN_LINE) return true;

        return false;
    }

    private boolean checkLeftDiagonal(int x, int y, List<Point> points) {
        int count = 1;
        for(int i = 1; i<MAX_COUNT_IN_LINE; i++){
            if(points.contains(new Point(x-i, y+i))){
                count++;
            }else {
                break;
            }
        }
        if(count == MAX_COUNT_IN_LINE) return true;

        for(int i = 1; i<MAX_COUNT_IN_LINE; i++){
            if(points.contains(new Point(x+i, y-i))){
                count++;
            }else {
                break;
            }
        }
        if(count == MAX_COUNT_IN_LINE) return true;

        return false;
    }

    private boolean checkRightDiagonal(int x, int y, List<Point> points) {
        int count = 1;
        for(int i = 1; i<MAX_COUNT_IN_LINE; i++){
            if(points.contains(new Point(x-i, y-i))){
                count++;
            }else {
                break;
            }
        }
        if(count == MAX_COUNT_IN_LINE) return true;

        for(int i = 1; i<MAX_COUNT_IN_LINE; i++){
            if(points.contains(new Point(x+i, y+i))){
                count++;
            }else {
                break;
            }
        }
        if(count == MAX_COUNT_IN_LINE) return true;

        return false;
    }

    private void drawPieces(Canvas canvas) {
        for(int i=0, n=mWhiteArray.size(); i< n; i++){
            Point whitePoint = mWhiteArray.get(i);
            canvas.drawBitmap(mWhitePiece,
                    (whitePoint.x + (1-radioPieceOfLineHeight)/2) * mLineHeight,
                    (whitePoint.y + (1-radioPieceOfLineHeight)/2) * mLineHeight, null);
        }

        for(int i=0, n=mBlackArray.size(); i< n; i++){
            Point blackPoint = mBlackArray.get(i);
            canvas.drawBitmap(mBlackPiece,
                    (blackPoint.x + (1-radioPieceOfLineHeight)/2) * mLineHeight,
                    (blackPoint.y + (1-radioPieceOfLineHeight)/2) * mLineHeight, null);
        }
    }

    //绘制棋盘
    private void drawBoard(Canvas canvas) {
        int w = mPanelWidth;
        float lineHeight = mLineHeight;

        for(int i=0; i<MAX_LINE; i++){
            int startX = (int) (0.5 * lineHeight);
            int endX = (int) (mPanelWidth - 0.5 * lineHeight);
            int y = (int) ((0.5 + i) * mLineHeight);
            canvas.drawLine(startX, y, endX, y, paint);
            canvas.drawLine(y, startX, y, endX, paint);
        }
    }

    //再来一局
    public void start(){
        mWhiteArray.clear();
        mBlackArray.clear();
        mIsGameOver = false;
        mIsWhiteWinner = false;
        invalidate();
    }

    private static final String INSTANCE = "instance";
    private static final String INSTANCE_GAME_OVER = "instance_game_over";
    private static final String INSTANCE_WHITE_ARRAY = "instance_white_array";
    private static final String INSTANCE_BLACK_ARRAY = "instance_black_array";

    @Nullable
    @Override
    protected Parcelable onSaveInstanceState() {
        Bundle bundle = new Bundle();
        bundle.putParcelable(INSTANCE, super.onSaveInstanceState());
        bundle.putBoolean(INSTANCE_GAME_OVER, mIsGameOver);
        bundle.putParcelableArrayList(INSTANCE_WHITE_ARRAY, mWhiteArray);
        bundle.putParcelableArrayList(INSTANCE_BLACK_ARRAY, mBlackArray);

        return bundle;
    }

    @Override
    protected void onRestoreInstanceState(Parcelable state) {
        if(state instanceof Bundle){
            Bundle bundle = (Bundle) state;
            mIsGameOver = bundle.getBoolean(INSTANCE_GAME_OVER);
            mWhiteArray = bundle.getParcelableArrayList(INSTANCE_WHITE_ARRAY);
            mBlackArray = bundle.getParcelableArrayList(INSTANCE_BLACK_ARRAY);
            super.onRestoreInstanceState(bundle.getParcelable(INSTANCE));
            return;
        }

        super.onRestoreInstanceState(state);
    }

    public void setData(WuziData wuziData) {
        this.mIsWhiteWinner = wuziData.ismIsWhiteWinner();
        this.mIsWhite = wuziData.ismIsWhite();
        this.mIsGameOver = wuziData.ismIsGameOver();
        this.mWhiteArray = wuziData.getmWhiteArray();
        this.mBlackArray = wuziData.getmBlackArray();

        invalidate();
    }
}
